package com.alibaba.cloud.application.handler;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.alibaba.cloud.application.handler.message.MessageHandler;
import com.alibaba.cloud.domain.MessageEvent;
import com.lmax.disruptor.EventHandler;

import lombok.extern.slf4j.Slf4j;

/**
 * @author cruise
 */
@Component
@Slf4j
public class MessageEventHandler implements ApplicationContextAware, EventHandler<MessageEvent> {
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void onEvent(MessageEvent event, long sequence, boolean endOfBatch) throws Exception {
        log.info("消息处理：{}", event.getBaseMessage());
        Map<String, MessageHandler> beans = applicationContext.getBeansOfType(MessageHandler.class);
        beans.forEach((key, value) -> value.execute(event.getBaseMessage()));
    }
}
